package com.yisu.auction.api.web.controller;

import com.alibaba.fastjson.JSON;
import com.yisu.auction.api.core.service.*;
import com.yisu.auction.api.domain.request.BasePage;
import com.yisu.auction.api.domain.request.indexPackage.AdvertisementRequest;
import com.yisu.auction.api.domain.request.prizePackage.PersonageCollectRequest;
import com.yisu.auction.api.domain.request.prizePackage.PrizeListRequest;
import com.yisu.auction.api.domain.response.indexPackage.UpgradeParamResponse;
import com.yisu.auction.api.domain.response.prizePackage.*;
import com.yisu.auction.api.domain.vo.goodsInfoPackageVos.ClosingBidRecordVo;
import com.yisu.auction.api.domain.vo.indexPackageVos.*;
import com.yisu.auction.api.web.interceptor.IAuthVerifyAnnotation;
import com.yisu.auction.api.domain.response.indexPackage.IndexInfoResponse;

import com.yisu.auction.ewf.common.enums.LoginTypeEnum;
import com.yisu.auction.ewf.common.utils.DateUtil;
import com.yisu.auction.ewf.common.web.JsonResult;
import com.yisu.auction.ewf.entity.SystemConfig;
import org.apache.calcite.linq4j.Linq4j;
import org.apache.calcite.linq4j.function.Predicate1;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * author: 赵杰
 * Business Description：首页相关业务接口
 * createTime：2017/8/11
 */
@Controller
@RequestMapping(value = "/index")
public class IndexController extends BaseController {
    @Resource
    private IAdvertisementService iAdvertisementService;
    @Resource
    private IPrizeService iPrizeService;
    @Resource
    private IMessageService iMessageService;
    @Resource
    private IPersonageCollectService iPersonageCollectService;
    @Resource
    private IOfferPriceLogService iOfferPriceLogService;
    @Resource
    private ISystemConfigService iSystemConfigService;


    /**
     * author: 赵杰
     * Business Description：获取首页相关业务信息
     *
     * @param
     * @return 系统参数
     */
    @RequestMapping(value = "/getUpgradeParam", method = {RequestMethod.POST, RequestMethod.GET}, produces = "application/json; charset=utf-8")
    @ResponseBody
    @IAuthVerifyAnnotation(Desc = "登录验证", LoginTypeEnum = LoginTypeEnum.NO_NEED_LOGIN)
    public JsonResult getUpgradeParam(final BasePage basePage) {
        JsonResult jsonResult = new JsonResult();
        UpgradeParamResponse upgradeParamResponse = new UpgradeParamResponse();
        UpgradeParamVo upgradeParamVo = new UpgradeParamVo();
        try {
            SystemConfigVo systemConfigVo = iSystemConfigService.getSystemConfigByKey("UpgradeParam");
            if (systemConfigVo != null) {
                List<UpgradeParamVo> upgradeParamVos = JSON.parseArray(systemConfigVo.getConfigValue(), UpgradeParamVo.class);
                if (!CollectionUtils.isEmpty(upgradeParamVos)) {
                    upgradeParamVo = Linq4j.asEnumerable(upgradeParamVos).where(new Predicate1<UpgradeParamVo>() {
                        @Override
                        public boolean apply(UpgradeParamVo upgradeParamVo) {
                            return upgradeParamVo.getAppType().toString().equals(basePage.getAppType()) && upgradeParamVo.getAppSign().equals(basePage.getAppSign());
                        }
                    }).firstOrDefault();
                }
            }
        } catch (Exception e) {
            logger.error("获取首页相关业务信息异常：" + e.getMessage());
        }
        upgradeParamResponse.setUpgradeParamVo(upgradeParamVo);
        jsonResult.setData(upgradeParamResponse);
        return jsonResult;
    }


    /**
     * author: 赵杰
     * Business Description：获取首页相关业务信息
     *
     * @param
     * @return 系统参数
     */
    @RequestMapping(value = "/getIndexInfo", method = {RequestMethod.POST, RequestMethod.GET}, produces = "application/json; charset=utf-8")
    @ResponseBody
    @IAuthVerifyAnnotation(Desc = "登录验证", LoginTypeEnum = LoginTypeEnum.NO_NEED_LOGIN)
    public JsonResult getIndexInfo(BasePage basePage) {
        JsonResult jsonResult = new JsonResult();
        IndexInfoResponse indexInfoResponse = new IndexInfoResponse();
        try {
            //首页广告业务
            List<AdvertisementVo> advertisementVos = iAdvertisementService.getAdvertisementList(new AdvertisementRequest(basePage.getAppSign()));
            if (!CollectionUtils.isEmpty(advertisementVos)) {
                for (AdvertisementVo advertisementVo : advertisementVos) {
                    if (!StringUtils.isEmpty(advertisementVo.getUrl())) {
                        BannerVo bannerVo = JSON.parseObject(advertisementVo.getUrl(), BannerVo.class);
                        if (bannerVo != null) {
                            advertisementVo.setUrl(bannerVo.getUrl());
                            advertisementVo.setNeedLogin(bannerVo.getNeedLogin());
                        }
                    } else {
                        if (advertisementVo.getProductId() != null) {
                            advertisementVo.setProductId(iPrizeService.getNextPeriodPrizeIdByGoodsId(advertisementVo.getProductId()));
                            advertisementVo.setUrl("treasurebox://ddbaoxiang.com/goodsDetail/" + advertisementVo.getProductId());
                        }
                    }
                }
            }
            indexInfoResponse.setAdvertisementVos(advertisementVos);
            //首页正在进行的商品业务
            PrizeListRequest prizeListRequest = new PrizeListRequest();
            prizeListRequest.setPageindex(1);
            prizeListRequest.setPagesize(10);
            prizeListRequest.setListType(1);
            prizeListRequest.setAppSign(basePage.getAppSign());
            prizeListRequest.setAppType(basePage.getAppType());
            List<PrizeListVo> prizeListVos = iPrizeService.getPrizeList(prizeListRequest);
            for (PrizeListVo item : prizeListVos) {
                item = convertCommon(item, basePage);
                if (!StringUtils.isEmpty(item.getImage())) {
                    item.setImage(Linq4j.asEnumerable(item.getImage().split(",")).toList().get(0));
                }
                if (!this.getAllowAuction()) {
                    item.setStatus(-100);
                }
            }
            indexInfoResponse.setPrizeListVos(prizeListVos);
            //首页拍卖头条跑马灯业务
            List<MessageVo> messageVos = iMessageService.getFrontPageList();
            indexInfoResponse.setMessageVos(messageVos);
        } catch (Exception e) {
            logger.error("获取首页相关业务信息异常：" + e.getMessage());
        }
        jsonResult.setData(indexInfoResponse);
        return jsonResult;
    }


    /**
     * getPrizeListForIndex+getIndexInfo 公用方法
     *
     * @param item
     * @param basePage
     * @return
     * @throws Exception
     */
    protected PrizeListVo convertCommon(PrizeListVo item, BasePage basePage) throws Exception {
        item.setCollectStatus(0);
        if (!StringUtils.isEmpty(basePage.getUserToken())) {
            this.userToken = basePage.getUserToken();
            basePage.setMemberId(String.valueOf(this.getToken().getMemberId()));
            PersonageCollectRequest personageCollectRequest = new PersonageCollectRequest();
            personageCollectRequest.setPrizeId(Integer.parseInt(String.valueOf(item.getPrizeId())));
            personageCollectRequest.setMemberId(basePage.getMemberId());
            if (iPersonageCollectService.collectStatus(personageCollectRequest))
                item.setCollectStatus(1);
        }
        ClosingBidRecordVo closingBidRecordVo = iOfferPriceLogService.getClosingBidRecordByPrizeId(item.getPrizeId());
        if (closingBidRecordVo != null) {
            item.setNickname(closingBidRecordVo.getNickname());
            item.setOfferPriceDate(simpleDateFormat.format(closingBidRecordVo.getOfferPriceDate()));
            item.setTransactionPrice(item.getTransactionPrice());
            int second = 10 - (int) (DateUtil.diffValue(this.getDbDate(), closingBidRecordVo.getOfferPriceDate()) / 1000);
            item.setBeginCountDown(second);
        }
        Long nextPeriodPrizeId = iPrizeService.getNextPeriodPrizeIdByPrizeId(item.getPrizeId());
        item.setNextPeriodPrizeId(nextPeriodPrizeId);
        return item;
    }

    /**
     * author: 赵杰
     * Business Description：获取首页各种状态的竞品列表
     *
     * @param
     * @return 系统参数
     */
    @RequestMapping(value = "/getPrizeListForIndex", method = {RequestMethod.POST}, produces = "application/json; charset=utf-8")
    @ResponseBody
    @IAuthVerifyAnnotation(Desc = "登录验证", LoginTypeEnum = LoginTypeEnum.NO_NEED_LOGIN)
    public JsonResult getPrizeListForIndex(PrizeListRequest prizeListRequest) {
        JsonResult jsonResult = new JsonResult();
        PrizeListResponse prizeListResponse = new PrizeListResponse();
        this.userToken = prizeListRequest.getUserToken();
        prizeListRequest.setMemberId(String.valueOf(this.getToken().getMemberId()));
        try {
            List<PrizeListVo> prizeListVos = iPrizeService.getPrizeList(prizeListRequest);
            for (PrizeListVo item : prizeListVos) {
                BasePage basePage = new BasePage();
                basePage.setAppSign(prizeListRequest.getAppSign());
                basePage.setUserToken(prizeListRequest.getUserToken());
                item = convertCommon(item, basePage);
                if (!StringUtils.isEmpty(item.getImage())) {
                    item.setImage(Linq4j.asEnumerable(item.getImage().split(",")).toList().get(0));
                }
                if (!this.getAllowAuction()) {
                    item.setStatus(-100);
                }
            }
            prizeListResponse.setPrizeListVos(prizeListVos);
        } catch (Exception e) {
            logger.error("获取首页各种状态的竞品列表异常：" + e.getMessage());
        }
        jsonResult.setData(prizeListResponse);
        return jsonResult;
    }


}
